package com.yiqi.liebang.feature.mine.view;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.baiiu.filter.ClassifyBo;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.google.gson.Gson;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.suozhang.framework.framework.AM;
import com.suozhang.framework.framework.BaseActivity;
import com.suozhang.framework.utils.T;
import com.yiqi.liebang.R;
import com.yiqi.liebang.common.util.GetJsonDataUtil;
import com.yiqi.liebang.entity.bo.JsonBean;
import com.yiqi.liebang.entity.bo.UserCardBo;
import com.yiqi.liebang.entity.bo.UserCenterBo;
import com.yiqi.liebang.entity.bo.UserDataBo;
import com.yiqi.liebang.feature.home.view.ClassifyActivity;
import com.yiqi.liebang.feature.mine.contract.UserContract;
import com.yiqi.liebang.feature.mine.dependencies.login.DaggerUserComponent;
import com.yiqi.liebang.feature.mine.dependencies.login.UserPresenterModule;
import com.yiqi.liebang.framework.DataServer;

import org.json.JSONArray;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;

public class EditUserCardActivity extends BaseActivity implements UserContract.View, Toolbar.OnMenuItemClickListener {

    private final static int REQUESTCODE = 1; // 返回的结果码
    @BindView(R.id.toolbar)
    Toolbar mToolbar;
    @BindView(R.id.iv_user_head)
    ImageView mIvUserHead;
    @BindView(R.id.tv_user_biaoqian)
    TextView mTvUserBiaoqian;
    @BindView(R.id.edt_user_name)
    EditText mEdtUserName;
    @BindView(R.id.edt_user_industry)
    EditText mEdtUserIndustry;
    @BindView(R.id.tv_user_city)
    TextView mTvUserCity;
    @BindView(R.id.tv_user_address)
    EditText mTvUserAddress;
    @BindView(R.id.tv_user_mobile)
    EditText mTvUserMobile;
    @BindView(R.id.tv_user_email)
    EditText mTvUserEmail;
    private String mLabelsId = "";

    private List<LocalMedia> selectList;
    private String mHeadUri, mCompanyUri;

    private List<JsonBean> options1Items = new ArrayList<>();
    private List<List<String>> options2Items = new ArrayList<>();
    private List<List<List<String>>> options3Items = new ArrayList<>();
    private Thread thread;
    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private static final int MSG_LOAD_FAILED = 0x0003;

    private boolean isLoaded = false;
    ArrayList<ClassifyBo> mLabelList = null;
    @Inject
    UserContract.Presenter mPresenter;

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_edit_user_card;
    }

    @Override
    protected void initInjector() {
        DaggerUserComponent.builder().userPresenterModule(new UserPresenterModule(this)).build().inject(this);
    }

    @Override
    protected void initView() {
        mToolbar.inflateMenu(R.menu.menu_save);
        initToolBar(mToolbar, "编辑名片信息", true, true);
        mToolbar.setOnMenuItemClickListener(this);

    }


    @Override
    protected void initData() {
        mPresenter.getUserCardData();
        mHandler.sendEmptyMessage(MSG_LOAD_DATA);
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_DATA:
                    if (thread == null) {//如果已创建就不再重新创建子线程了
//                        Toast.makeText(EditOtherActivity.this, "Begin Parse Data", Toast.LENGTH_SHORT).show();
                        thread = new Thread(new Runnable() {
                            @Override
                            public void run() {
                                // 子线程中解析省市区数据
                                initJsonData();
                            }
                        });
                        thread.start();
                    }
                    break;

                case MSG_LOAD_SUCCESS:
//                    Toast.makeText(EditOtherActivity.this, "Parse Succeed", Toast.LENGTH_SHORT).show();
                    isLoaded = true;
                    break;

                case MSG_LOAD_FAILED:
                    T.showShort("Parse Failed");
                    finish();
                    break;
            }
        }
    };

    @OnClick({R.id.btn_edit_touxiang, R.id.btn_edit_name, R.id.btn_edit_hangye, R.id.btn_edit_biaoqian, R.id.btn_edit_diqu, R.id.btn_edit_address, R.id.btn_edit_phone, R.id.btn_edit_email})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_edit_touxiang:
                initGallery(PictureConfig.SINGLE);
                break;
            case R.id.btn_edit_name:
                break;

            case R.id.btn_edit_hangye:
                break;
            case R.id.btn_edit_biaoqian:
                Intent intent = new Intent(this, ClassifyActivity.class);
                intent.putExtra("classify", mLabelList);
                intent.putExtra("isSelect", true);
                startActivityForResult(intent, 6);
                break;
            case R.id.btn_edit_diqu:
                if (isLoaded) {
                    showPickerView();
                } else {
                    T.showShort("Please waiting until the data is parsed");
                }
                break;
            case R.id.btn_edit_address:
                break;
            case R.id.btn_edit_phone:
                break;
            case R.id.btn_edit_email:
                break;
        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == -1) {
            switch (requestCode) {
                case PictureConfig.SINGLE:
                    // 图片选择结果回调
                    selectList = PictureSelector.obtainMultipleResult(data);
                    for (int i = 0; i < selectList.size(); i++) {
                        mHeadUri = selectList.get(i).getCutPath();
                    }
                    AM.image().bindToCircleObject(mHeadUri, mIvUserHead);
                    break;
                case PictureConfig.CAMERA:
                    break;
                case 6:
                    mLabelList = data.getParcelableArrayListExtra("labels");
                    if (mLabelList != null && mLabelList.size() > 0) {
                        String lables = "";
                        mLabelsId = "";
                        for (int i = 0; i < mLabelList.size(); i++) {
                            lables += mLabelList.get(i).getClassify() + ",";
                            mLabelsId += mLabelList.get(i).getId() + ",";
                        }
                        mLabelsId = mLabelsId.substring(0, mLabelsId.length() - 1);
                        mTvUserBiaoqian.setText(lables.substring(0, lables.length() - 1));
                    }else {
                        mLabelsId =null;
                        mTvUserBiaoqian.setText("");
                    }
                    break;
            }
        }
    }


    private void initGallery(int pos) {
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())
                .theme(R.style.picture_default_style1)
                .selectionMode(PictureConfig.SINGLE)// 多选 or 单选
                .previewImage(true)// 是否可预览图片
                .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                .isCamera(true)
                .enableCrop(true)// 是否裁剪
                .circleDimmedLayer(true)// 是否圆形裁剪 true or false
                .withAspectRatio(1, 1)// int 裁剪比例 如16:9 3:2 3:4 1:1 可自定义
                .compress(true)// 是否压缩
                .hideBottomControls(false)// 是否显示uCrop工具栏，默认不显示
                .isGif(false)// 是否显示gif图片
                .freeStyleCropEnabled(true)// 裁剪框是否可拖拽
                .circleDimmedLayer(true)// 是否圆形裁剪
                .selectionMedia(selectList)// 是否传入已选图片
                .scaleEnabled(true)
                .forResult(pos);//结果回调onActivityResult code
    }

    @Override
    public void showUserCenterSuccess(UserCenterBo s) {

    }

    @Override
    public void showUserCenterError(String error) {


    }

    @Override
    public void showUserCardSuccess(UserCardBo s) {
        showUserInfo(s);
    }

    @Override
    public void showMineSuccess(UserDataBo s) {

    }

    @Override
    public void showLikeSuccess() {

    }

    @Override
    public void showPrivateSuccess(Boolean error) {

    }

    @Override
    public void showUserEditSuccess() {
        showMsg("修改成功！");
        finish();
    }

    @Override
    public void showDeleteFriendSuccess() {

    }

    @Override
    public void showAddBlackSuccess() {

    }

    private void showUserInfo(UserCardBo s) {
        if (s == null) return;
        mLabelList = new ArrayList<>(s.getClassify());
        AM.image().bindToCircleObject(s.getUserHead(), mIvUserHead);
        mEdtUserName.setText(TextUtils.isEmpty(s.getUserName()) ? "" : s.getUserName());
        mEdtUserIndustry.setText(TextUtils.isEmpty(s.getUserIndustry()) ? "" : s.getUserIndustry());
        mTvUserBiaoqian.setText((s.getClassify() != null && s.getClassify().size() > 0
                ? DataServer.getClassfiyStr2(s.getClassify()) : ""));
        mTvUserCity.setText(TextUtils.isEmpty(s.getUserWorkAddress()) ? "" : s.getUserWorkAddress());
        mTvUserAddress.setText(TextUtils.isEmpty(s.getUserDetailAddress()) ? "" : s.getUserDetailAddress());
        mTvUserMobile.setText(TextUtils.isEmpty(s.getPhone()) ? "" : s.getPhone());
        mTvUserEmail.setText(TextUtils.isEmpty(s.getUserEmail()) ? "" : s.getUserEmail());

    }

    @Override
    public void showError(String error) {
        showMsg("" + error);
    }

    private void showPickerView() {// 弹出选择器

        OptionsPickerView pvOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String tx = options1Items.get(options1).getPickerViewText() +
                        options2Items.get(options1).get(options2);
                mTvUserCity.setText(tx);

            }
        })

                .setTitleText("城市选择")
                .setDividerColor(R.color.div_primary)
                .setLineSpacingMultiplier(2.5f)
                .setTextColorCenter(R.color.text_primary) //设置选中项文字颜色
                .setContentTextSize(15)
                .build();


        pvOptions.setPicker(options1Items, options2Items);//三级选择器
        pvOptions.show();
    }

    private void initJsonData() {//解析数据

        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */
        String JsonData = new GetJsonDataUtil().getJson(this, "province.json");//获取assets目录下的json文件数据

        List<JsonBean> jsonBean = parseData(JsonData);//用Gson 转成实体


        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = jsonBean;

        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            List<String> CityList = new ArrayList<>();//该省的城市列表（第二级）
            List<List<String>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）

            for (int c = 0; c < jsonBean.get(i).getCityList().size(); c++) {//遍历该省份的所有城市
                String CityName = jsonBean.get(i).getCityList().get(c).getName();
                CityList.add(CityName);//添加城市
                List<String> City_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean.get(i).getCityList().get(c).getArea() == null
                        || jsonBean.get(i).getCityList().get(c).getArea().size() == 0) {
                    City_AreaList.add("");
                } else {
                    City_AreaList.addAll(jsonBean.get(i).getCityList().get(c).getArea());
                }
                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.add(CityList);

            /**
             * 添加地区数据
             */
            options3Items.add(Province_AreaList);
        }

        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);

    }


    public List<JsonBean> parseData(String result) {//Gson 解析
        List<JsonBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                JsonBean entity = gson.fromJson(data.optJSONObject(i).toString(), JsonBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
            mHandler.sendEmptyMessage(MSG_LOAD_FAILED);
        }
        return detail;
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
        }
    }


    @Override
    public boolean onMenuItemClick(MenuItem item) {
        if (item.getItemId() == R.id.action_next) {
            mPresenter.editUserCardData(
                    mHeadUri,
                    mEdtUserName.getText().toString(),
                    mLabelsId,
                    mEdtUserIndustry.getText().toString(),
                    mTvUserCity.getText().toString(),
                    mTvUserAddress.getText().toString(),
                    mTvUserMobile.getText().toString(),
                    mTvUserEmail.getText().toString()
            );
        }
        return false;
    }
}
